/* eslint-disable import/no-extraneous-dependencies */
import { Modal, Upload, message } from 'antd';
import { useState, useCallback, useMemo, useEffect } from 'react';
import { useDispatch, useSelector } from 'dva';
import { exceptSpace } from '@/utils/utils';
import { exportExcelWithJson } from '@/utils/export';
import * as api from '../services/list';

export default function useMakeList({ status }) {
  const paginationData = useSelector(({ global }) => global.paginationData);
  const searchData = useSelector(({ global }) => global.searchData);
  const dispatch = useDispatch();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [fileList, setFileList] = useState([]);

  // --- 列表 ---
  const [list, setList] = useState([]);

  // --- loading状态 ---
  const [loading, setLoading] = useState(false);
  const [downloadPending, setDownloadPending] = useState(false);
  const [uploadPending, setUploadPending] = useState(false);

  const getQueryParams = () => {
    const { params } = searchData;

    return exceptSpace({
      params,
      pageNum: paginationData.current || 1,
      pageSize: paginationData.pageSize || 10,
      type: status,
    });
  };

  const getList = useCallback(() => {
    if (status > -1) {
      setLoading(true);
      api
        .getList(getQueryParams())
        .then(res => {
          if (res.success) {
            dispatch({
              type: 'global/saveTableInfo',
              payload: {
                paginationData: { ...paginationData, total: res?.data?.total || 0 },
              },
            });
            const { pageSize = 10, current = 1 } = paginationData;
            setList(
              res?.data?.records?.map((item, index) => ({
                ...item,
                __index: (current - 1) * pageSize + index + 1,
              })) || [],
            );
          }
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [getQueryParams, paginationData]);

  const downloadExcel = useCallback(id => {
    setDownloadPending(true);
    exportExcelWithJson(
      '/api',
      {
        id,
      },
      () => {
        setDownloadPending(false);
      },
    );
  }, []);

  const batchDownloadExcel = useCallback(() => {
    if (selectedRowKeys.length === 0) {
      message.warn('请先勾选需要下载的信息');
      return;
    }

    setDownloadPending(true);
    exportExcelWithJson(
      '/api',
      {
        selectedRowKeys,
      },
      () => {
        setDownloadPending(false);
        setSelectedRowKeys([]);
      },
    );
  }, [getQueryParams, selectedRowKeys]);

  const uploadExcel = useCallback(
    e => {
      e.stopPropagation();
      if (fileList.length > 0) {
        setUploadPending(true);
        api
          .uploadExcel({ file: fileList[0].originFileObj })
          .then(res => {
            if (res.success) {
              setFileList([]);
              getList();
            } else {
              setFileList(prev => [
                {
                  ...prev[0],
                  response: res?.message || '导入失败，请重试',
                  status: 'error',
                },
              ]);
            }
          })
          .catch(err => {
            message.warn(err?.message || '导入失败，请重试');
            setFileList(prev => [
              {
                ...prev[0],
                response: err?.message || '导入失败，请重试',
                status: 'error',
              },
            ]);
          })
          .finally(() => {
            setUploadPending(false);
          });
      }
    },
    [fileList, getList],
  );

  const handleUploadFileChange = useCallback(({ fileList }) => {
    const f = fileList.slice(-1);
    setFileList(f);
  }, []);

  const handleBeforeUpload = useCallback(file => {
    const isExcel =
      file.type === 'application/vnd.ms-excel' ||
      file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    if (!isExcel) {
      message.warn('请上传Excel文件');
      return Upload.LIST_IGNORE;
    }

    return false;
  }, []);

  const deleteItem = useCallback(
    params => {
      api.deleteItem(params).then(res => {
        if (res.success) {
          getList();
        }
      });
    },
    [getList],
  );

  const batchDelete = useCallback(() => {
    Modal.confirm({
      title: '确认删除',
      content: '是否删除选中数据？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        return api
          .batchDelete({
            ids: selectedRowKeys.join(','),
          })
          .then(res => {
            if (res.success) {
              getList();
              setSelectedRowKeys([]);
            }
          });
      },
    });
  }, [selectedRowKeys, getList]);

  const rowSelection = useMemo(
    () => ({
      onChange: selectedRowKeys => {
        setSelectedRowKeys(selectedRowKeys);
      },
      selectedRowKeys,
      preserveSelectedRowKeys: true,
      fixed: true,
      getCheckboxProps: record => ({
        disabled: record.transportNum === 0 || record.transportMode === 2,
      }),
    }),
    [selectedRowKeys],
  );

  const handleClearSelectedRowKeys = useCallback(() => {
    setSelectedRowKeys([]);
  }, [setSelectedRowKeys]);

  useEffect(() => {
    getList();
  }, [searchData, status]);

  useEffect(() => {
    setSelectedRowKeys([]);
  }, [status]);

  return {
    selectedRowKeys,
    setSelectedRowKeys,
    rowSelection,
    list,
    setList,
    getList,
    deleteItem,
    batchDelete,
    downloadExcel,
    batchDownloadExcel,
    downloadPending,
    fileList,
    uploadExcel,
    uploadPending,
    handleUploadFileChange,
    handleBeforeUpload,
    loading,
    setLoading,
    handleClearSelectedRowKeys,
  };
}
